﻿using System;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

[Serializable]
public class MovementAndRotateAsset : PlayableAsset, ITimelineClipAsset, IJumpableAsset
{
    #region ITimelineClipAsset
    public ClipCaps clipCaps
    {
        get
        {
            return ClipCaps.None;
        }
    }

    #endregion

    #region IJumpableAsset
    public TimeInfo TimeInfo { get; set; }
    public TrackAsset OwnerTrack { get; set; }
    #endregion

    public ExposedReference<Transform> Target;
    public MovementAndRotateBehaviour template;

    public override Playable CreatePlayable(PlayableGraph graph, GameObject owner)
    {
        //Debug.Log("PlayableAsset.CreatePlayable");

        //Debug.LogFormat("IJumpableAsset [{0}] Get : Track[{1}], [{2}~{3}]",
        //    GetInstanceID(), 
        //    null == OwnerTrack ? "null" : OwnerTrack.GetInstanceID().ToString(),
        //    null == TimeInfo ? "null" : TimeInfo.start.ToString(),
        //    null == TimeInfo ? "null" : TimeInfo.end.ToString() );

        //if (null != owner)
        //{
        //    //组件PlayableDirector放置的对象
        //    Debug.Log("CreatePlayable : " + owner.name);
        //}

        var playable = ScriptPlayable<MovementAndRotateBehaviour>.Create(graph, template);

        //没得啥子用处
        //Debug.Log("GetLeadTime : " + playable.GetLeadTime());
        //Debug.Log("GetDuration : " + playable.GetDuration());
        //Debug.Log("GetPreviousTime : " + playable.GetPreviousTime());

        Transform t = Target.Resolve(playable.GetGraph().GetResolver());

        MovementAndRotateBehaviour behaviour = playable.GetBehaviour();

        Type type = behaviour.GetType();
        if (typeof(IJumpableBehaviour).IsAssignableFrom(type))
        {
            IJumpableBehaviour jumpableBehaviour = behaviour;
            jumpableBehaviour.OwnerTrack = OwnerTrack;
            jumpableBehaviour.TimeInfo = TimeInfo;

            jumpableBehaviour.Director = owner.GetComponent<PlayableDirector>();
            jumpableBehaviour.PlayableAsset = this;
        }

        //After IJumpableBheaviour
        behaviour.Init(t);

        return playable;
    }
}
